import requests
import time
import hashlib
import base64
from Crypto.Cipher import AES


def get_md5(val, is_hex=True):
    md5 = hashlib.md5()
    md5.update(val.encode())
    if is_hex:
        return md5.hexdigest()
    else:
        return md5.digest()


url = "https://dict.youdao.com/webtranslate"

# （1）构建逆向动态值
mysticTime = str(int(time.time() * 1000))
print(mysticTime)

d = 'fanyideskweb'
e = mysticTime
u = 'webfanyi'
t = 'fsdsogkndfokasodnaso'
s = f"client={d}&mysticTime={e}&product={u}&key={t}"
print("s:::", s)
sign = get_md5(s)

# （2）请求模拟
data = {
    "i": "apple",
    "from": "auto",
    "to": "",
    "dictResult": "true",
    "keyid": "webfanyi",
    "sign": sign,
    "client": "fanyideskweb",
    "product": "webfanyi",
    "appVersion": "1.0.0",
    "vendor": "web",
    "pointParam": "client,mysticTime,product",
    "mysticTime": mysticTime,
    "keyfrom": "fanyi.web",
    "mid": 1,
    "screen": 1,
    "model": 1,
    "network": "wifi",
    "abtest": 0,
    "yduuid": "abcdefg",
}
my_headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
    "Referer": "https://fanyi.youdao.com/",
    "Cookie": "OUTFOX_SEARCH_USER_ID_NCOO=1837136861.99783; OUTFOX_SEARCH_USER_ID=2039883963@103.156.184.202; UM_distinctid=18acc0c423c8a-067b7d9f92c33d-18525634-1d73c0-18acc0c423d1300; P_INFO=golang13121758648; ANTICSRF=cleared; NTES_OSESS=cleared; S_OINFO="
}
res = requests.post(url, data=data, headers=my_headers)
res_encrypt_base64 = res.text.replace("-", "+").replace("_", "/")
print("res_encrypt_base64:::", res_encrypt_base64)

# （3）解码和解密数据

# 解码
res_encrypt = base64.b64decode(res_encrypt_base64)
print("res_encrypt:::", res_encrypt)
# AES解密

# 密钥
o = 'ydsecret://query/key/B*RGygVywfNBwpmBaZg*WT7SIOUP2T0C9WHMZN39j^DAdaZhAnxvGcCY6VYFwnHl'
n = 'ydsecret://query/iv/C@lZe2YzHtZ2CYgaXKSVfsb7Y4QWHjITPPZ0nQp87fBeJ!Iv6v^6fvi2WN@bYpJ4'

key = get_md5(o, is_hex=False)
# 偏移量
iv = get_md5(n, is_hex=False)
# 解密
# 构建aes算法对象
aes = AES.new(key, AES.MODE_CBC, iv)
source_data = aes.decrypt(res_encrypt).decode()
print("source_data:", source_data)
